package com.scy.java.thread;

public class SaleTicketDemo {
    public static void main(String[] args) {
        //创建资源对象
        Ticket ticket = new Ticket();
        //启动多个线程操作资源类的对象
        Thread t1 = new Thread("窗口1"){
            @Override
            public void run() {

                //使用同步代码块将售票方法进行同步
                while (true){
                    if (ticket.getTicket() == 0){
                        return;
                    }
//                    synchronized (ticket){
                        ticket.saleTicket();//售票
//                    }
                }
            }
        };
        Thread t2 = new Thread("窗口2"){
            @Override
            public void run() {

                while (true){
                    if (ticket.getTicket() == 0){
                    return;
                }
//                    synchronized (ticket){
                        ticket.saleTicket();//售票
//                    }
                }
            }
        };
        Thread t3 = new Thread("窗口3"){
            @Override
            public void run() {

                while (true){
                    if (ticket.getTicket() == 0){
                        return;
                    }
//                    synchronized (ticket){
                        ticket.saleTicket();//售票
//                    }
                }
            }
        };
        //启动多线程
        t1.start();
        t2.start();
        t3.start();

    }

}
//抽取资源
 class Ticket{
    private int ticket = 100;
    //买票的方法

    /**
     * 给方法上添加synchronized关键字，表示该方法是 同步方法
     */
    public synchronized void saleTicket(){
        if (ticket>0){
            //模拟出票
            System.out.println(Thread.currentThread().getName()
                    +"卖出了1张票，票号："+ticket);
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            ticket--;
        }else {
            System.out.println("票已售罄");
        }
    }
    public int getTicket(){
        return ticket;
    }
}












